define(function (require, exports, module) {
    var myPub = require('./public');
    var oGoUpPage = $('.js_goUpPage');                                  // 顶部分会上一页按钮
    var oMinute = $('.js_min');                                         // 显示分钟区域
    var oSecond = $('.js_sec');                                         // 显示秒钟区域
    var oSubmitBCpopArea = $('.js_submitBCpopArea');                    // 提示框区域
    var oSubmitBCpop = $('.js_submitBCpop');                            // 提示框标题
    var oSubmitBCpopTip = $('.js_submitBCpopTip');                      // 提示框提示内容
    var oSubmitCancle = $('.js_submitCancle');                          // 放弃按钮
    var oSubmitNow = $('.js_submitNow');                                // 继续支付按钮
    var oReSubmit = $('.js_reSubmit');                                  // 重新下单按钮
    var oPayBtn = $('.js_payBtn');                                      // 确认支付按钮


    module.exports = {
      init:function () {
          // 执行点击事件
          detail.clickEvent();

          detail.CutDataTime();
      }  
    };

    var detail = {
        time_CutTime : null,          // 定时器
        timeLimit : 30,               // 倒计时的分钟数
        valid: true,                  // 订单是否有效
        offTap: true,                 // 防止确认支付按钮双击
        tap_timer: null,              // 防止双击定时器

        // 点击事件
        clickEvent:function(){
            var _this = this;

            // 顶部返回上一页按钮
            oGoUpPage.on('click',function (e) {
                if(_this.valid){
                    // 显示提示框
                    var tips = '超过订单支付时效后，订单将被取消，请尽快完成支付';
                    oSubmitBCpopArea.show();
                    oSubmitBCpop.show();
                    oSubmitBCpopTip.text(tips);
                    oSubmitNow.show();
                    oReSubmit.hide();
                }else{
                    console.log('返回上一页')
                    // window.history.go(-1);
                    window.history.back();
                }
                e.stopPropagation();
            });

            // 放弃按钮
            oSubmitCancle.on('click',function (e) {
                window.history.go(-1);
                e.stopPropagation();
            });

            // 继续支付按钮
            oSubmitNow.on('click',function (e) {
                oSubmitBCpopArea.hide();
                e.stopPropagation();
            });

            // 重新下单按钮
            oReSubmit.on('click',function (e) {
                window.history.go(-1);
                e.stopPropagation();
            });

            // 确认支付按钮
            oPayBtn.on('click',function () {
                if(!_this.offTap)return;
                _this.offTap = false;
                submitHiPoPay(merchantNo,amount,openid,currency,productInfo,sysTradeNo,notifyUrl,_this);
                clearTimeout(_this.tap_timer);
                _this.tap_timer = setTimeout(function () {
                    _this.offTap = true;
                },300)
            })
        },

        // 倒计时
        CutDataTime : function () {
            var _this = this;
            var startTime = createDate*1;                                 // 订单创建时间
            var nowDate = new Date();
            var now = nowDate.getTime();                                // 现在的时间
            var endTime = startTime*1+_this.timeLimit*60*1000*1;            // 订单结束时间
            var leftTime = endTime*1 - now*1;
            clearTimeout(_this.time_CutTime);
            var mm, ss;
            if(leftTime >= 0) {
                _this.valid = true;
                mm = Math.floor(leftTime / 1000 / 60 % 60);
                ss = Math.floor(leftTime / 1000 % 60);

                ss = ss < 10 ? ('0' + ss) : ss;
                mm = mm < 10 ? ('0' + mm) : mm;
                clearTimeout(_this.time_CutTime);
                _this.time_CutTime = setTimeout(function () {
                    _this.CutDataTime()
                }, 1000);

            }else{
                _this.valid = false;
                ss = '0' + 0;
                mm = '0' + 0;

                // 显示提示框
                var tips = '订单已超时，请重新下单';
                oSubmitBCpopArea.show();
                oSubmitBCpop.hide();
                oSubmitBCpopTip.text(tips);
                oSubmitNow.hide();
                oReSubmit.show();

            }
            oMinute.text(mm);
            oSecond.text(ss);
        }
    }


    var js_api_param = {};
    function jsApiCall(_this) {
        WeixinJSBridge.invoke('getBrandWCPayRequest', js_api_param, function (res) {

            if (res.errMsg == "chooseWXPay:ok") {
                myPub.TipLayerEnd('支付成功','no',function () {
                    _this.offTap = true;
                    // window.location.href = bases + "/member/order/tradeSuccess?orderSn=" + orderSnNo + "&sessionUid=" + sessionUid;
                    window.location.href = bases + "/h/goodspay/paymentOver?orderSn=" + orderSnNo + "&sessionUid=" + sessionUid;
                })

            } else {
                myPub.TipLayerEnd('支付失败','no',function () {
                    _this.offTap = true;
                    localStorage.setItem("orderNav_index",1);
                    window.location.href = bases + "/shop/pay/order_list";
                })
            }

            if (res.err_msg == "get_brand_wcpay_request:ok") {
                alert('支付成功');
                myPub.TipLayerEnd('支付成功','no',function () {
                    _this.offTap = true;
                    // window.location.href = bases + "/member/order/tradeSuccess?orderSn=" + orderSnNo + "&sessionUid=" + sessionUid;
                    window.location.href = bases + "/h/goodspay/paymentOver?orderSn=" + orderSnNo + "&sessionUid=" + sessionUid;
                })
            }
            if (res.err_msg == "get_brand_wcpay_request:cancel") {
                alert('取消支付');
                myPub.TipLayerEnd('取消支付','no',function () {
                    _this.offTap = true;
                    localStorage.setItem("orderNav_index",1);
                    window.location.href = bases + "/shop/pay/order_list";
                })
            }
            if (res.err_msg == "get_brand_wcpay_request:fail") {
                alert('支付失败');
                myPub.TipLayerEnd('支付失败','no',function () {
                    _this.offTap = true;
                    localStorage.setItem("orderNav_index",1);
                    window.location.href = bases + "/shop/pay/order_list";
                })
            }
        });
    }

    function  submitHiPoPay(merchantNo,amount,openid,currency,productInfo,sysTradeNo,notifyUrl,_this) {
        console.log("商户号为："+merchantNo);
        console.log("金额为："+amount);
        console.log("openid为："+openid);
        console.log("支付回调地址为："+notifyUrl);
        $.ajax({
            async: true,
            url: 'https://api.wisecashier.com',
            type: 'POST',
            data: {
                'merchant_no': merchantNo,
                'amount': amount,
                'openid':openid,
                'currency': currency,
                'product_info': productInfo,
                'agent_order_id': sysTradeNo,
                'notify_url': notifyUrl,
                'is_rmb': 'TRUE'

            },
            headers: {
                'Version': '1.0'
            },
            beforeSend: function () {
            },
            success: function (r) {
                console.log("ajax方法success回调逻辑开始");
                console.log(r.meta.status_code);
                console.log(r.meta.message);
                console.log(r.meta.success);
                if (r.meta.success) {
                    js_api_param = r.data.js_param;
                    if (typeof WeixinJSBridge == "undefined") {
                        if (document.addEventListener) {
                            document.addEventListener('WeixinJSBridgeReady', jsApiCall(_this), false);
                        } else if (document.attachEvent) {
                            document.attachEvent('WeixinJSBridgeReady', jsApiCall(_this));
                            document.attachEvent('onWeixinJSBridgeReady', jsApiCall(_this));
                        }
                    } else {
                        jsApiCall(_this);
                    }
                }else {
                    console.log("hiPo判断，不允许唤起支付!");
                }

                console.log("ajax方法success回调逻辑结束");
            },
            complete: function () {
            }
        });
    }
});